iT邦幫忙

2022 iThome 鐵人賽

DAY 17
0
自我挑戰組

Udemy課程上完你也可以開始Codewars 30天系列 第 17

[Day17] Codewars >>> Compute the Largest Sum of all Contiguous Subsequences (Python)

  • 分享至 

  • xImage
  •  

題目(5kyu):

Given an array of numbers, calculate the largest sum of all possible blocks of >consecutive elements within the array. The numbers will be a mix of positive and >negative values. If all numbers of the sequence are nonnegative, the answer will be the >sum of the entire array. If all numbers in the array are negative, your algorithm >should return zero. Similarly, an empty array should result in a zero return from your >algorithm.

largestSum([-1,-2,-3]) == 0
largestSum([]) == 0
largestSum([1,2,3]) == 6
Easy, right? This becomes a lot more interesting with a mix of positive and negative >numbers:

largestSum([31,-41,59,26,-53,58,97,-93,-23,84]) == 187
The largest sum comes from elements in positions 3 through 7: 59+26+(-53)+58+97 == 187

Once your algorithm works with these, the test-cases will try your submission with >increasingly larger random problem sizes.

解題思路

題目理解:設計一函數代入皆一為數字的列表arr,嘗試去找到列表的所有連續組合中,其合最大的值並返還。
可以透過max()在遞迴中比較當前最大連續和來實現:

def largest_sum(arr):
    """嘗試找到arr中所有連續數組的合之最大值"""
    #若為空集合依題目直接返還0
    if arr == []:return 0
    #設計變數儲存當前連續累計的總和
    sum_now = 0
    #設計變數儲存目前最大連續和
    max_sum_reslut = 0

    for num in arr:
        #若num的值 < sum_now+num,則讓sum_now加上num的值以繼續累加連續和
        #若num的值 > sum_now+num,代表num本身大於先前連續組合之和,故讓其取代原先的sum_now成為新  的連續組合開頭並重新累計值
        sum_now = max(num, sum_now + num)
        #將上一個連續和與目前最大連續和做比較,若當前連續和更大則取代成為新max_sum_reslut
        max_sum_reslut = max(max_sum_reslut,sum_now)
    #最終return時需注意若max_sum_reslut的值為負數,代表整個arr中並無正整數,依題目指示需返還0
    return max_sum_reslut if max_sum_reslut>0 else 0

上一篇
[Day16] Codewars >>> Mean Square Error (Python)
下一篇
[Day18] Codewars >>> Probabilities for Sums in Rolling Cubic Dice (Python)
系列文
Udemy課程上完你也可以開始Codewars 30天30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言